import calendar
import qrcode
from PyQt5.QtWidgets import *
from myutil import globalvar as gl, logs
from myutil.api.kcb_api import *
from ui.ics_form import Ui_Form as main_weight


class ics_form(QWidget, main_weight):
    def __init__(self, parent=None):
        super(ics_form, self).__init__(parent)
        self.setupUi(self)

        self.user_info_dict = None

        self.check_date_pushButton.setEnabled(True)
        self.get_ics_res_label.setVisible(False)

        self.check_date_pushButton.clicked.connect(self.check_date_event)
        self.get_ics_pushButton.clicked.connect(self.get_ics_event)

    def check_date_event(self):
        logs.logs_print("检查日期")

        self.user_info_dict = gl.get_value("user_info")
        if self.user_info_dict is None:
            self.date_status_label.setText(
                '<html><head/><body><p align="center"><span style=" font-weight:600; color:#ff0000;">请先进行登录，再使用此工具</span></p></body></html>')
            return 0

        date = str(self.first_day_dateEdit.text())

        year = int(date.split("/")[0])
        month = int(date.split("/")[1])
        day = int(date.split("/")[2])
        cal = calendar.weekday(year, month, day)

        if str(cal) == "0":
            self.date_status_label.setText('日期检查正确')
            self.date = "{:0>4}{:0>2}{:0>2}".format(year, month, day)
            self.get_ics_pushButton.setEnabled(True)
        else:
            week_day_dict = {0: '星期一', 1: '星期二', 2: '星期三', 3: '星期四', 4: '星期五', 5: '星期六', 6: '星期天', }
            self.date_status_label.setText('日期检查错误，请填写这个学期开始的第一周星期一的日期，当前为：' + week_day_dict.get(int(cal)))

    def get_ics_event(self):
        logs.logs_print("获取日历")
        phone_system = self.phone_system_comboBox.currentText()

        stu_name = self.user_info_dict.get("stu_name")

        save_data_from_cookie(self.user_info_dict.get("cookie"))  # 选课结果.json保存文件完成...
        use_data = json_read_to_data_json()  # 读取选课结果
        class_info_list_data = processing_data(use_data)

        file_name = ""
        if phone_system == "ios-(iphone,ipad)":
            ics_list_wz = get_ics_wz_list(class_info_list_data, stu_name, first_week_mo=self.date,
                                          week_num=21, select_system="2")
            file_name = get_ics_file_from_list(ics_list_wz, system_str="IOS")
        else:
            ics_list_wz = get_ics_wz_list(class_info_list_data, stu_name, first_week_mo=self.date,
                                          week_num=21, select_system="1")
            file_name = get_ics_file_from_list(ics_list_wz, system_str="Android")

        try:
            a = gl.get_value("ssh_diver")
            logs.logs_print("file_name:" + file_name)
            res = a.upload_file(file_path="./{}".format(file_name),
                                remote_dir_path='/root/apache/www/ics/{}'.format(file_name))
            if res == False:
                a = 1 / 0

            url = "http://wp19991.cn:83/ics/" + file_name
            logs.logs_print("url " + url)
            img = qrcode.make(url)
            save_name = "手机扫描此二维码，获取日历" + file_name.split(".")[0] + ".png"
            img.show()
            img.save(save_name)

            mysql = gl.get_value("mysql_diver")
            res = mysql.add_one("INSERT INTO app_key_value(`key`, `value`) VALUES (%s, %s);",
                                ["jwc_kcb_{}_".format(file_name) + stu_name, "str(use_data)"])
            logs.logs_print(res)
            if os.path.exists(file_name):
                os.remove(file_name)
        except:
            self.get_ics_res_label.setText(
                '<html><head/><body><p align="center"><span style=" font-size:11pt; font-weight:600; '
                'color:#00aa00;">课程表日历已经写入完成</span></p><p align="center"><span style=" font-size:11pt; '
                'font-weight:600; color:#00aa00;">目录下的 </span><span style=" font-size:11pt; font-weight:600; '
                'color:#ff0000;">*.ics文件</span><span style=" font-size:11pt; font-weight:600; color:#00aa00;"> '
                '为日历文件</span></p><p align="center"><span style=" font-size:11pt; font-weight:600; '
                'color:#00aa00;">感谢你的使用,可以分享给你周围的同学使用</span></p><p align="center"><span style=" font-size:11pt; '
                'font-weight:600; color:#00aa00;">🐳</span></p></body></html>')
            self.get_ics_status_label.setText("完成")
            self.get_ics_res_label.setVisible(True)
            logs.logs_print("完成")

        self.get_ics_status_label.setText("完成")
        self.get_ics_res_label.setVisible(True)
        self.get_ics_pushButton.setEnabled(False)
